package com.hnkywl.sts.util;

import com.jianzhou.sdk.BusinessService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;

/**
 * 发送短信工具类
 * User: ccr
 * Date: 13-5-21
 * Time: 上午10:15
 * To change this template use File | Settings | File Templates.
 */
public class SMSUtils {
    private Log logger = LogFactory.getLog(this.getClass());
//    private URL url;            //http://211.144.37.143:9901/SendSms.aspx
    private String Username;    //whgzjq 见配置
    private String password;    //zjq5840550
    private String signature;    //短信签名
    /**
     * 批次号。
     * 批次号是短信提交的序列号, 最大长度为15, 可以为 1,2,3,…… 等数字序列,
     * 也可以为用户随意定义的数字串, 也可以为当前的UTC时间戳, 但该字段长度不能超过15,
     * 作用主要用于区分不同批次的提交。(该字符串不能含有数字以外的字符),批次号不做处理
     * 直接带入本次提交的返回值中
     */
//    private String batch;

    private static SMSUtils uniqueInstance = null; // 单例模式

    public static SMSUtils getInstance(){
        if (uniqueInstance == null) {
            uniqueInstance = new SMSUtils();
        }
        return uniqueInstance;
    }

    /**
     * 参数由用户来定
     * @param username
     * @param password
     */
    /*public SMSUtils(String url,String username,String password,String batch){
        this.setUrl(url);
        this.password = password;
        this.Username = username;
        this.batch = batch;
    }*/
    public SMSUtils(String username, String password, String signature){
        this.password = password;
        this.Username = username;
        this.signature = signature;
    }

    /**
     * 参数从数据库中取得  单例
     */
    private SMSUtils(){
        //从数据库获取
        Session session =((SessionFactory) ApplicationInstance.getBean("sessionFactory")).getCurrentSession();
        String hql = "select z from Sjzdz where bm = ?";
//        String u = (String) session.createQuery(hql).setParameter(0,"url").uniqueResult();
        this.Username = (String) session.createQuery(hql).setParameter(0,"Username").uniqueResult();
        this.password = (String) session.createQuery(hql).setParameter(0,"password").uniqueResult();
        this.signature = (String) session.createQuery(hql).setParameter(0,"signature").uniqueResult();
        signature = (signature == null ? "" : signature);
//        this.setUrl(u);
//        this.batch = "0";
    }

    /*private void setUrl(String url) {
        try {
            this.url = new URL(url);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }*/

    /**
     * 发送短信
     * @param mobiles 发送短信号码列表
     * @param content 发送内容
     * @return 返回发送状态
     */
    /*public String send(List<String> mobiles,String content) throws Exception {
        String mobileString = StringUtils.join(mobiles, ",");
        return send(mobileString,content);
    }*/
    public int send(List<String> mobiles,String content) throws Exception {
        String mobileString = StringUtils.join(mobiles, ";");
        return send(mobileString,content);
    }

    /*public String send(String mobileString,String content) throws Exception {
        URLConnection conn = url.openConnection();
        this.send(this.getPostParam(mobileString,content),conn);
        String result = URLDecoder.decode(this.getContent(conn), "GB2312");
        if(result.equals("0")){
            this.logger.info("发送成功:"+content);
        }else if(result.equals("101")){
            this.logger.info("发送失败:用户名或密码不能为空");
            throw new Exception("发送失败:用户名或密码不能为空");
        } else if(result.equals("102")){
            this.logger.info("发送失败:手机号码或短信内容不能为空");
            throw new Exception("发送失败:手机号码或短信内容不能为空");
        } else if(result.equals("103")){
            this.logger.info("发送失败:手机号码含有非法号码");
            throw new Exception("发送失败:手机号码含有非法号码");
        } else if(result.equals("104")){
            this.logger.info("发送失败:批次号格式错误");
            throw new Exception("发送失败:批次号格式错误");
        } else if(result.equals("105")){
            this.logger.info("发送失败:用户名或密码错误");
            throw new Exception("发送失败:用户名或密码错误");
        } else if(result.equals("106")){
            this.logger.info("发送失败:用户账号已停用");
            throw new Exception("发送失败:用户账号已停用");
        } else if(result.equals("107")){
            this.logger.info("发送失败:用户账号异常");
            throw new Exception("发送失败:用户账号异常");
        } else if(result.equals("108")){
            this.logger.info("发送失败:号码内容重复发送");
            throw new Exception("发送失败:号码内容重复发送");
        } else if(result.equals("109")){
            this.logger.info("发送失败:内容中含有非法关键字");
            throw new Exception("发送失败:内容中含有非法关键字");
        } else if(result.equals("110")){
            this.logger.info("发送失败:余额不足");
            throw new Exception("发送失败:余额不足");
        } else if(result.equals("111")){
            this.logger.info("发送失败:系统错误");
            throw new Exception("发送失败:系统错误");
        }else{
            this.logger.info("发送失败:未知错误");
            throw new Exception("发送失败:未知错误");
        }
        return result;
    }*/
    public int send(String mobileString,String content) throws Exception {
        BusinessService bs = new BusinessService();
        bs.setWebService("http://www.jianzhou.sh.cn/JianzhouSMSWSServer/services/BusinessService");
        int result = bs.sendBatchMessage(this.Username, this.password, mobileString, content+this.signature);
        if (result>0) {
            this.logger.info("发送成功:"+content);
        } else {
            switch (result) {
                case -1:
                    this.logger.info("账户余额不足");
                    throw new Exception("账户余额不足");
                case -2:
                    this.logger.info("帐号或密码错误");
                    throw new Exception("帐号或密码错误");
                case -3:
                    this.logger.info("连接服务商失败");
                    throw new Exception("连接服务商失败");
                case -4:
                    this.logger.info("超时");
                    throw new Exception("超时");
                case -5:
                    this.logger.info("其他错误");
                    throw new Exception("其他错误");
                case -6:
                    this.logger.info("短信内容为空");
                    throw new Exception("短信内容为空");
                case -7:
                    this.logger.info("目标号码为空");
                    throw new Exception("目标号码为空");
                case -8:
                    this.logger.info("用户通道设置不对，需要设置三个通道");
                    throw new Exception("用户通道设置不对，需要设置三个通道");
                case -9:
                    this.logger.info("捕获未知异常");
                    throw new Exception("捕获未知异常");
                case -10:
                    this.logger.info("超过最大定时时间限制");
                    throw new Exception("超过最大定时时间限制");
                case -11:
                    this.logger.info("目标号码在黑名单里");
                    throw new Exception("目标号码在黑名单里");
                case -12:
                    this.logger.info("消息内容包含禁用词语");
                    throw new Exception("消息内容包含禁用词语");
                case -13:
                    this.logger.info("没有权限使用该网关");
                    throw new Exception("没有权限使用该网关");
                case -14:
                    this.logger.info("找不到对应的Channel ID");
                    throw new Exception("找不到对应的Channel ID");
                case -17:
                    this.logger.info("没有提交权限");
                    throw new Exception("没有提交权限");
                case -20:
                    this.logger.info("超速提交(一般为每秒一次提交)");
                    throw new Exception("超速提交(一般为每秒一次提交)");
                default:
                    this.logger.info("未知错误");
                    throw new Exception("未知错误");
            }
        }
        return result;
    }

   /* private String getPostParam(String mobileString,String content) throws UnsupportedEncodingException {
        StringBuilder param = new StringBuilder();
        param.append("Username="+this.Username);
        param.append("&");
        param.append("password="+this.password);
        param.append("&");
        param.append("batch="+this.batch);
        param.append("&");
        param.append("mobilelist="+mobileString);
        param.append("&");
        param.append("msgcontent="+ URLEncoder.encode(content,"GB2312"));
        return param.toString();
    }*/

    /**
     * 发送短信
     * 发送短信的Url形式:http://211.144.37.143:9901/SendSms.aspx
     * content参数:Username=whgzjq&password=zjq5840550&batch=1&mobilelist=180xxxxxxxx&msgcontent=xxxx
     * @param content 发短信的内容
     */
    /*private void send(String content,URLConnection conn) {
        conn.setDoInput(true);
        conn.setDoOutput(true);
        try {
            PrintWriter output = new PrintWriter(conn.getOutputStream());;
            output.print(content);
            output.close();
        } catch (IOException e) {
            this.logger.error("发送短信失败:"+e);
        }
    }*/

    /**
     * 返回访问网站后的回应
     * @return 返回发送状态 0:发送成功
     *                    101:用户名或密码不能为空
     *                    102:手机号码或短信内容不能为空
     *                    103:手机号码含有非法号码
     *                    104:批次号格式错误
     *                    105:用户名或密码错误
     *                    106:用户账号已停用
     *                    107:用户账号异常
     *                    108:号码内容重复发送
     *                    109|非法关键字:内容中含有非法关键字
     *                    110:余额不足
     *                    111:系统错误
     */
    /*private String getContent(URLConnection conn) {
        String line, result = "";
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
        } catch (IOException ex) {
            this.logger.error("获取失败:"+ex);
        }
        return result;
    }*/
}
